package com.kurumi.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.kurumi.config.MyConfig;
import com.kurumi.pojo.MedicalRecordPageTrace;
import com.kurumi.pojo.RespondResult;
import com.kurumi.pojo.resource.MedicalRecordResource;
import com.kurumi.query.MedicalRecordQuery;
import com.kurumi.query.MedicalRecordScanQuery;
import com.kurumi.service.BaseInfoService;
import com.kurumi.service.MedicalRecordScanService;
import com.kurumi.service.MedicalRecordService;
import com.kurumi.service.MedicalRecordTraceService;
import com.kurumi.thread.MedicalRecordPDFThread;
import com.kurumi.util.DateUtil;
import com.kurumi.util.ExcelUtils;
import com.kurumi.util.FileUtil;
import com.kurumi.util.GuidUtil;
import com.kurumi.util.JsonUtil;
import com.kurumi.util.StringUtil;
import com.kurumi.util.WaterMarkUtil;

@Controller
@RequestMapping("/medical_record_scan")
public class MedicalRecordScanController {

	@Autowired
	private MyConfig myConfig;
	
	@Autowired
	private BaseInfoService baseInfoService;
	
	@Autowired
	private MedicalRecordService medicalRecordService;
	
	@Autowired
	private MedicalRecordScanService medicalRecordScanService;
	
	@Autowired
	private MedicalRecordTraceService medicalRecordTraceService;
	
	@GetMapping("/scan_send_page")
	public String scanSendPage(Model model){
		return "scan/scan_send_page";
	}
	
	@GetMapping("/scan_upload")
	public String scanUpload(String errorCode,Model model){
		model.addAttribute("errorCode", errorCode);
		return "scan/scan_upload";
	}
	/**
	 * 第三方扫描文件上传检索
	 * @param errorCode
	 * @param model
	 * @return
	 */
	@GetMapping("/third_scan_query_page")
	public String thirdScanQueryPage(Model model){
		return "scan/third_scan_query_page";
	}
	
	/**
	 * 第三方扫描文件上传page
	 * @param errorCode
	 * @param model
	 * @return
	 */
	@GetMapping("/third_scan_upload_page")
	public String thirdScanUploadPage(String errorCode,Model model){
		model.addAttribute("errorCode", errorCode);
		return "scan/third_scan_upload_page";
	}
	
	
	@GetMapping("/scan_image_pagination")
	public String scanImagePagination(String mrId,Model model){
		model.addAttribute("mrId", mrId);
		return "scan/scan_image_pagination";
	}
	
	
	@GetMapping("/ajax_query_scan_send")
	@ResponseBody
	public RespondResult ajaxQueryScanSend(MedicalRecordQuery params){
		RespondResult respondResult = null;
		
		try{
			List<Map<String,Object>> medicalRecords = new ArrayList<Map<String,Object>>();
			int count = 0;
			if(!params.querySignedEmpty()){
				//medicalRecords = medicalRecordScanService.getMedicalRecordOfScanSend(params);
				//count= medicalRecordScanService.getMedicalRecordCountOfScanSend(params);
				medicalRecords = medicalRecordScanService.getMedicalRecordScanSend(params);
				count= medicalRecordScanService.getMedicalRecordCountScanSend(params);
			}
			
			params.setTotalCounts(count);
			params.setQueryDatas(medicalRecords);
			respondResult = new RespondResult(true, RespondResult.successCode, null, params);
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), params);
		}
		
		return respondResult;
	}
	
	@PostMapping("/ajax_scan_send")
	@ResponseBody
	public RespondResult ajaxScanSend(String visitGuid){
		RespondResult respondResult = null;
		
		try{
			Subject subject=SecurityUtils.getSubject();
			Session session = subject.getSession();
			Map<String, Object> currentUser = (Map<String, Object>)session.getAttribute("currentUser");
			String userCode =(String)currentUser.get("user_code");
			String userName =(String)currentUser.get("user_name");
			MedicalRecordPageTrace putwayPageTrace = new MedicalRecordPageTrace();
			
			putwayPageTrace.setVisitGuid(visitGuid);
			putwayPageTrace.setCreateUserId(userCode);
			putwayPageTrace.setCreateUserName(userName);
			putwayPageTrace.setTraceTypeCode(MedicalRecordPageTrace.VISIT_SCAN);
			putwayPageTrace.setTraceTypeName(MedicalRecordPageTrace.VISIT_SCAN_NAME);
			putwayPageTrace.setTraceDateTime(new Date());
			int count = medicalRecordTraceService.insertMedicalRecordPageTrace(putwayPageTrace);
			if(count == 1){
				respondResult = new RespondResult(true, RespondResult.successCode, "扫描交接成功", "扫描交接成功");
			}else{
				respondResult = new RespondResult(true, RespondResult.errorCode, "扫描交接失败", "扫描交接失败");
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), "");
		}
		
		return respondResult;
	}
	
	@GetMapping("/export_scan_send_xls")
	public void exportScanSendXLS(MedicalRecordQuery params,String beyondDay,HttpServletResponse response) {
		OutputStream out = null;
		try{
			List<Map<String,Object>> medicalRecords = new ArrayList<Map<String,Object>>();
			if(!params.querySignedEmpty()){
				params.setPageSize(null);
				medicalRecords = medicalRecordScanService.getMedicalRecordOfScanSend(params);
			}
			/*response.setContentType("octets/stream");*/
			/*response.setCharacterEncoding("GBK");*/
			response.setContentType("applicationnd.ms-excel");
			String title= "病案扫描交接"+DateUtil.dateFormat(new Date());
			StringBuilder downLoadFileName = new StringBuilder();
			downLoadFileName = new StringBuilder(
					"attachment;filename=");
			downLoadFileName.append(title)
					.append(".xls");
			/*downLoadFileName.append(title).append(DateUtil.dateFormat(new Date()))
			.append(".dbf");*/
			String encodeStr = new String(downLoadFileName.toString().getBytes(
					"GB2312"), "ISO_8859_1");
			response.addHeader("Content-Disposition", encodeStr);
			out = response.getOutputStream();
			List<String> headers = new ArrayList<String>();
			headers.add("住院号");/*
			header.add("病案号");
			header.add("住院次数");*/
			headers.add("姓名");
			headers.add("科别");
			headers.add("出院日期");
			List<String> keys = new ArrayList<String>();
			keys.add("only_id");
			keys.add("patient_name");
			keys.add("out_dept_name");
			keys.add("out_hospital_date");
			
			List<Map<String, String>> records = new ArrayList<Map<String,String>>();
			for (Map<String, Object> medicalRecord : medicalRecords) {
				Map<String, String> record = new HashMap<String, String>();
				record.put("only_id",(String)medicalRecord.get("only_id"));
				record.put("patient_name",(String)medicalRecord.get("patient_name"));
				record.put("out_dept_name",(String)medicalRecord.get("out_dept_name"));
				record.put("out_hospital_date",(String)medicalRecord.get("out_hospital_date"));
				records.add(record);
			}
			ExcelUtils.exportExcel(out, title, headers, keys, records);
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			if(out != null){
				try {
					out.flush();
				} catch (Exception e2) {
					// TODO: handle exception
				}
				try {
					out.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
			
		}
		
	}
	
	@GetMapping("/ajax_query_scan")
	@ResponseBody
	public RespondResult ajaxQueryScan(MedicalRecordScanQuery params){
		RespondResult respondResult = null;
		
		try{
			List<Map<String,Object>> medicalRecords = new ArrayList<Map<String,Object>>();
			int count = 0;
			if(!params.isEmpty()){
				medicalRecords = medicalRecordScanService.getMedicalRecordOfScan(params);
				count= medicalRecordScanService.getMedicalRecordCountOfScan(params);
			}
			
			params.setTotalCounts(count);
			params.setQueryDatas(medicalRecords);
			respondResult = new RespondResult(true, RespondResult.successCode, null, params);
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), params);
		}
		
		return respondResult;
	}
	
	@PostMapping(value = "/images_upload")
	public String imagesUpload(@RequestParam("uploadImages")MultipartFile[] uploadImages,@RequestParam("visitGuid")String visitGuid,HttpServletRequest request) {
		try{
			if(uploadImages!=null && uploadImages.length>0){
				medicalRecordScanService.scanImagesUpload(visitGuid, uploadImages);
				List<Map<String,Object>> medicalRecords = medicalRecordService.getMedicalRecordByVisitGuid(visitGuid);
				String mrId = (String)medicalRecords.get(0).get("mr_id");
				return "redirect:/medical_record_scan/scan_image_pagination?mrId="+mrId;
			}else{
				return "redirect:/medical_record_scan/scan_upload?errorCode=1";
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "redirect:/medical_record_scan/scan_upload?errorCode=2";
		}
		
	}
	
	@GetMapping("/image_pagination")
	public String imagePagination(String visitGuid, Model model){
		Map<String, List<Map<String, Object>>> baseInfo = new HashMap<String, List<Map<String,Object>>>();
		List<Map<String, Object>> mrPageTypes = baseInfoService.getMrPageTypes();
		baseInfo.put("mrPageTypes", mrPageTypes);
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		Map<String, Object> datas = new HashMap<String,Object>();
		
		List<Map<String,Object>> medicalRecords = medicalRecordService.getMedicalRecordByVisitGuid(visitGuid);
		List<Map<String,Object>> pageTypeOfPaginations = medicalRecordScanService.getPaginationCountByVisitGuid(visitGuid);
		List<Map<String,Object>> scanFiles = medicalRecordScanService.getImageFilesByVisitGuid(visitGuid);
		datas.put("medicalRecord", medicalRecords.get(0));
		datas.put("scanFiles", scanFiles);
		datas.put("pageTypeOfPaginations", pageTypeOfPaginations);
		datas.put("visitGuid", visitGuid);
		String jsonDatas = JsonUtil.objectToJson(datas);
		model.addAttribute("jsonDatas", jsonDatas);
		return "scan/image_pagination";
	}
	
	
	@GetMapping("/ajax_image_stream")
	@ResponseBody
	public void ajaxImageStream(String fileHash,HttpServletResponse response){
		List<Map<String,Object>> imageFiles = medicalRecordScanService.getImageFileByFileHash(fileHash);
		Map<String,Object> imageFile = null;
		if(imageFiles.size() > 0){
			imageFile = imageFiles.get(0);
		}
		response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        String fileName = (String)imageFile.get("file_name");
        response.addHeader(
                "Content-Disposition",
                "attachment; filename=\""
                        + fileHash + "\"");
        String filePath = myConfig.getImageRecourcePath() + GuidUtil.getLocalPath(fileHash)+"\\"
        					+fileName;
        ServletOutputStream out;
        FileInputStream in = null;
		try {
			out = response.getOutputStream();
			in = new FileInputStream(filePath);
			 int len;
	            byte[] buffer = new byte[1024];
	            while ((len = in.read(buffer)) != -1) {
	                out.write(buffer, 0, len);
	            }
	            out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
            try {
                if (in != null) {
                    in.close();
                    in = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
	}
	
	@ResponseBody
	@PostMapping("/ajax_image_pagination")
	public RespondResult ajaxImagePagination(String visitGuid,String fileHash,String newPageTypeCode, Model model){
		try{
			int result = medicalRecordScanService.imagePagination(visitGuid, fileHash, newPageTypeCode);
			if(result == 0){
				
				return new RespondResult(true, RespondResult.errorCode, "编页失败", "编页失败");
			}else{
				List<Map<String,Object>> datas = medicalRecordScanService.getPaginationCountByVisitGuid(visitGuid);
				return new RespondResult(true, RespondResult.successCode, "编页成功", datas);
			}
		}catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
			return new RespondResult(false, RespondResult.errorCode, e.getMessage(), "编页失败");
		}
	}
	
	
	@ResponseBody
	@PostMapping("/ajax_image_pagination_finish")
	public RespondResult ajaxImagePaginationFinish(String visitGuid, Model model){
		try{
			int result = medicalRecordScanService.imagePaginationFinish(visitGuid);
			if(result == -2){
				return new RespondResult(true, RespondResult.lackCode, "编页完成失败", "基础资源缺失或存在未完成编页的图片");
			}else{
				try {
					List<Map<String,Object>> sourceFiles = medicalRecordScanService.getImageFilesByVisitGuid(visitGuid);
					
					MedicalRecordResource medicalRecordResource = new MedicalRecordResource();
					medicalRecordResource.getImageRecources().addAll(sourceFiles);
					medicalRecordResource.setImageBasicPath( myConfig.getImageRecourcePath());
					String newPDFPath = myConfig.getPdfRecourcePath()+StringUtil.getLocalPath(visitGuid)+ visitGuid+"\\"+"pagination_image.pdf";
					File newPDFFile = new File(newPDFPath);
					if(newPDFFile.exists()){
						newPDFFile.delete();
					}
					
					String publishPdfDir = myConfig.getPdfRecourcePath()+StringUtil.getLocalPath(visitGuid)+ visitGuid+"\\"+"publisih\\";
					List<String> publishPdfPaths = FileUtil.getChileFilePaths(publishPdfDir);
					for (String publishPdfPath : publishPdfPaths) {
						File publishPdfFile = new File(publishPdfPath);
						if(publishPdfFile.exists()){
							publishPdfFile.delete();
						}
					}
					
					medicalRecordResource.setNewPDFPath(newPDFPath);
					MedicalRecordPDFThread medicalRecordPDFThread = new MedicalRecordPDFThread(medicalRecordResource);
					medicalRecordPDFThread.start();
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				
				return new RespondResult(true, RespondResult.successCode, "编页完成", "编页完成");
			}
		}catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
			return new RespondResult(false, RespondResult.errorCode, e.getMessage(), "编页完成失败");
		}
	}
	
	
	@RequestMapping("/show_image_pagination")
	public void showImagePagination(String visitGuid, HttpServletResponse response) {
		
		ByteArrayOutputStream baos = null;

		
		try {
			OutputStream outStream = response.getOutputStream(); 
			String pdfPath = myConfig.getPdfRecourcePath()+StringUtil.getLocalPath(visitGuid)+ visitGuid+"\\"+"pagination_image.pdf";
			if(new File(pdfPath).exists()){
				baos = WaterMarkUtil.getOutputStreamOfWaterMarkByText(pdfPath, "仅可用于预览");
				
			}else{
				baos = new ByteArrayOutputStream();
				String errorPDF = myConfig.getPdfRecourcePath()+"error.pdf";
				FileInputStream inputStream = new FileInputStream(errorPDF);
				byte[] buffer = new byte[1024];
		        int len = 0;
		        while ((len = inputStream.read(buffer)) != -1 ) {  
		            baos.write(buffer, 0, len);  
		        }
		        baos.flush();
		        inputStream.close();
			}
			
			response.setContentLength(baos.size());
			response.setContentType("application/pdf");
			response.addHeader("Content-Disposition", "inline;FileName=show.pdf");
			
			outStream.write(baos.toByteArray(), 0, baos.size());  
			
			 
	        
	        outStream.flush(); 
	        outStream.close(); 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	@GetMapping("/remote_show_image_pagination")
	public void remoteShowImagePagination(String onlyId, HttpServletResponse response) {
		
		ByteArrayOutputStream baos = null;

		
		try {
			OutputStream outStream = response.getOutputStream();
			List<String> visitGuids = medicalRecordService.getVisitGuidByOnlyId(onlyId);
			String visitGuid = null;
			if(!visitGuids.isEmpty()){
				visitGuid = visitGuids.get(0);
			}
			
			if(visitGuid!= null){
				String pdfPath = myConfig.getPdfRecourcePath()+StringUtil.getLocalPath(visitGuid)+ visitGuid+"\\"+"pagination_image.pdf";
				if(new File(pdfPath).exists()){
					baos = WaterMarkUtil.getOutputStreamOfWaterMarkByText(pdfPath, "仅可用于预览");
					
				}else{
					baos = new ByteArrayOutputStream();
					String errorPDF = myConfig.getPdfRecourcePath()+"error.pdf";
					FileInputStream inputStream = new FileInputStream(errorPDF);
					byte[] buffer = new byte[1024];
			        int len = 0;
			        while ((len = inputStream.read(buffer)) != -1 ) {  
			            baos.write(buffer, 0, len);  
			        }
			        baos.flush();
			        inputStream.close();
				}
				
			}else{
				baos = new ByteArrayOutputStream();
				String errorPDF = myConfig.getPdfRecourcePath()+"error.pdf";
				FileInputStream inputStream = new FileInputStream(errorPDF);
				byte[] buffer = new byte[1024];
		        int len = 0;
		        while ((len = inputStream.read(buffer)) != -1 ) {  
		            baos.write(buffer, 0, len);  
		        }
		        baos.flush();
		        inputStream.close();
			}
			
			
			response.setContentLength(baos.size());
			response.setContentType("application/pdf");
			response.addHeader("Content-Disposition", "inline;FileName=show.pdf");
			
			outStream.write(baos.toByteArray(), 0, baos.size());  
			
			 
	        
	        outStream.flush(); 
	        outStream.close(); 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@GetMapping("/show_to_publish")
	public String showToPublish(Model model){
		return "publish/show_to_publish";
	}
	
	
	/**
	 * 第三方扫描文件上传
	 * @param file
	 * @param request
	 * @return
	 *//*
	@RequestMapping(value = "/third_scan_upload", method = RequestMethod.POST)
	public String thirdScanUpload(@RequestParam("files")MultipartFile[] files,HttpServletRequest request) {
		int count = 0;
		try {
			Subject subject=SecurityUtils.getSubject();
			Session session = subject.getSession();
			Map<String, Object> currentUser = (Map<String, Object>)session.getAttribute("currentUser");
			String userCode =(String)currentUser.get("user_code");
			String userName =(String)currentUser.get("user_name");
			System.out.println("文件数量:"+files.length);
			Map<String, UploadScan> uploadScanMap = new HashMap<String, UploadScan>();
			if(files!=null && files.length>0){
				for (MultipartFile multipartFile : files) {
					//文件原名称
					String originalFilename=multipartFile.getOriginalFilename();
					String[] splits = originalFilename.split("/");
					//文件名称
					
					String fileName =splits[splits.length-1];
					
					String folderName=splits[splits.length-2];
					UploadScan uploadScan = uploadScanMap.get(folderName);
					if(uploadScan == null){
						uploadScan=new  UploadScan();
						uploadScan.setCreateUserId(userCode);
						uploadScan.setCreateDate(new Date());
						uploadScan.setUploadDate(new Date());
						uploadScan.setOriginalFolder(folderName);
						uploadScanMap.put(folderName, uploadScan);
					}
					
					
					//文件流Hash（100位）
					String hashStr = new StringBuffer(GuidUtil.get36SystemHash(new String(multipartFile.getBytes()))).reverse().toString();
					
		
					//获取文件后缀名
					String fileSuffixes = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
					long fileSize = multipartFile.getSize();
					String fileSizeHashStr = GuidUtil.get36SystemHash(fileSize);
					
					//文件Hash
					String fileHash = new StringBuffer(hashStr).append(fileSizeHashStr).toString();
					System.err.println("fileHash：" + fileHash.length());
					ScanFile scanFile = new ScanFile();
					scanFile.setFileHash(fileHash);
					String localPath = GuidUtil.getLocalPath(hashStr);
					
					String remoteUrl = GuidUtil.getRemoteUrl(hashStr);
					
					
					//文件摘要后92位  文件摘要hash值 + 文件大小的5位hash值  
					 hashStr = hashStr.substring(8)+fileSizeHashStr.substring(0, 5);
					
					 
					//文件保存路径
					String filePath = myConfig.getImageRecourcePath() + localPath;
					File destFile = new File(filePath,hashStr+"."+fileSuffixes);
					if(!destFile.exists()){
						File destDir = new File(filePath);
						if(!destDir.exists()){
							destDir.mkdirs();
						}
						multipartFile.transferTo(destFile);
					}
					scanFile.setFileName(hashStr+"."+fileSuffixes);
					scanFile.setFileUrl(remoteUrl);
					scanFile.setCreateDate(new Date());
					scanFile.setFileType(fileSuffixes);
					scanFile.setOriginalName(fileName);
					
					uploadScan.getScanFiles().add(scanFile);
				
				}
			}
			count = medicalRecordScanService.thirdScanUpload(uploadScanMap);
		} catch (Exception e) {
			e.printStackTrace();
			count = -1;
		}
		return "redirect:/medical_record_scan/third_scan_upload_page?errorCode="+count;
		
	}
	
	@GetMapping("/ajax_third_scan_query")
	@ResponseBody
	public RespondResult ajaxThirdScanQuery(UploadScanQuery params){
		RespondResult respondResult = null;
		
		try{
			List<Map<String,Object>> records = new ArrayList<Map<String,Object>>();
			int count = 0;
			if(!params.isEmpty()){
				records = medicalRecordScanService.getUploadScanByQuery(params);
				count= medicalRecordScanService.getUploadScanCountByQuery(params);
			}
			
			params.setTotalCounts(count);
			params.setDatas(records);
			respondResult = new RespondResult(true, RespondResult.successCode, null, params);
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), params);
		}
		
		return respondResult;
	}*/
	
	/*@GetMapping("/ajax_medical_record_query")
	@ResponseBody
	public RespondResult ajaxMedicalRecordQuery(String mrId,Integer visitNumber){
		RespondResult respondResult = null;
		
		try{
			List<String> records = new ArrayList<String>();
			records = medicalRecordService.getVisitGuidByMrIdAndVisitNumber(mrId,visitNumber);
			respondResult = new RespondResult(true, RespondResult.successCode, null, records.size());
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), null);
		}
		
		return respondResult;
	}*/
	
	
	/*@PostMapping("/ajax_add_medical_record_relevance")
	@ResponseBody
	public RespondResult ajaxAddMedicalRecordRelevance(MedicalRecord medicalRecord,Integer uploadScanId){
		RespondResult respondResult = null;
		
		try{
			int count = medicalRecordService.checkMeditalRecordUniq(medicalRecord.getOnlyId(), medicalRecord.getMrId(), medicalRecord.getVisitNumber());
			if(count > 0){
				return new RespondResult(true, RespondResult.repeatCode, null, count);
			}
			count = medicalRecordScanService.addMedicalRecordRelevance(medicalRecord,uploadScanId);
			respondResult = new RespondResult(true, RespondResult.successCode, null, medicalRecord.getVisitGuid());
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), "");
		}
		
		return respondResult;
	}
	*/
	
	@PostMapping("/ajax_medical_record_relevance")
	@ResponseBody
	public RespondResult ajaxMedicalRecordRelevance(String mrId,Integer visitNumber,Integer uploadScanId){
		RespondResult respondResult = null;
		
		try{
			medicalRecordScanService.medicalRecordRelevance(mrId,visitNumber,uploadScanId);
			List<String> visitGuids = medicalRecordService.getVisitGuidByMrIdAndVisitNumber(mrId, visitNumber);
			respondResult = new RespondResult(true, RespondResult.successCode, null, visitGuids.get(0));
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), "");
		}
		
		return respondResult;
	}
	
	@RequestMapping("/paginationMedrecordImages")
	public String paginationMedrecordImages(String visitGuid,String paginationStatus, Model model,HttpServletRequest request){
		List<Map<String,Object>> hospitalizationNotes = medicalRecordService.getMedicalRecordByVisitGuid(visitGuid);
		model.addAttribute("hospitalizationNotes", hospitalizationNotes);
		if(StringUtils.isEmpty(paginationStatus)){
			paginationStatus="1";
		}
//		String currentUser = CookieUtils.getCookieValue(request, "userName");
//		TreatmentTrace treatmentTrace = new TreatmentTrace();
//		treatmentTrace.setUserId(currentUser);
//		treatmentTrace.setTreatmentGuid(firstGuid);
//		treatmentTraceService.addMedicalTrace(treatmentTrace,TreatmentTrace.VISIT_PAGINATION);
		List<Map<String,Object>> scanFiles = medicalRecordScanService.getPaginationScanFilesByFirstGuidAndPagination(visitGuid,paginationStatus);
		model.addAttribute("scanFiles", scanFiles);

		//编页的所有标签
		List<Map<String,Object>> mrPageTypes = medicalRecordScanService.getMrPageTypes();
		model.addAttribute("mrPageTypes", mrPageTypes);
		model.addAttribute("mrPageSizes", mrPageTypes.size());
		
		
		List<Map<String,Object>> mrPageTypesOfPagination = medicalRecordScanService.getMrPageTypesOfPaginationCountByFirstGuid(visitGuid);
		Map<Integer, Map<String,Object>> mrPageTypesOfPaginationMap = new HashMap<Integer, Map<String,Object>>();
		
		
		for (Map<String, Object> mrPageTypeOfPagination : mrPageTypesOfPagination) {
			mrPageTypesOfPaginationMap.put((Integer)mrPageTypeOfPagination.get("mr_page_type"), mrPageTypeOfPagination);
		}
		//System.out.println(mrPageTypesOfPaginationMap);
		model.addAttribute("visitGuid", visitGuid);
		model.addAttribute("paginationStatus", paginationStatus);
		model.addAttribute("mrPageTypesOfPaginationMap", mrPageTypesOfPaginationMap);
		/*model.addAttribute("hospitalizationNoteResourceUrl", myConfig.getImageRecourcePath());*/
		model.addAttribute("hospitalizationNoteResourceUrl", "http://localhost:8080/upload/");
		return "scan/medRecordImagePagination";
	}
	
	@ResponseBody
	@RequestMapping("/scanFilePaginationCount")
	public Map<String,Object> scanFilePaginationCount(String firstGuid){
		Map<String,Object> map = new HashMap<String,Object>();
		int scanFileCount = medicalRecordScanService.getScanFilePaginationCount(firstGuid, null);
	 	int unPaginationFileCount = medicalRecordScanService.getScanFilePaginationCount(firstGuid, "1");
	 	map.put("scanFileCount", scanFileCount);
	 	map.put("unPaginationFileCount", unPaginationFileCount);
	 	return map;
	}
	
	@ResponseBody
	@RequestMapping("/paginationMedrecordImage")
	public RespondResult paginationMedrecordImage(String firstGuid,String fileHash,Integer mrPageTypeId,Integer oldMrPageTypeId, Model model){
		
		int result = medicalRecordScanService.paginationMedrecordImage(firstGuid, fileHash, mrPageTypeId);
		
		if(result == 0){
			return new RespondResult(false, RespondResult.errorCode, "病案图片编页失败", null);
		}
		
		List<Integer> mrPageTypes = new ArrayList<Integer>();
		if(oldMrPageTypeId != null){
			mrPageTypes.add(oldMrPageTypeId);
		}
		mrPageTypes.add(mrPageTypeId);
		
		List<Map<String, Object>> resultMap = medicalRecordScanService.getMrPageTypesOfPaginationCountByFirstGuidAndMrPageTypes(firstGuid, mrPageTypes);
		Map<Integer, Map<String,Object>> mrPageTypesOfPaginationMap = new HashMap<Integer, Map<String,Object>>();
		for (Map<String, Object> mrPageTypeOfPagination : resultMap) {
			mrPageTypesOfPaginationMap.put((Integer)mrPageTypeOfPagination.get("mr_page_type"), mrPageTypeOfPagination);
		}
		//mrPageTypesOfPaginationMap.put("fileHash", fileHash);
		
		return new RespondResult(true, RespondResult.successCode, fileHash, mrPageTypesOfPaginationMap);
	}
	
	@ResponseBody
	@RequestMapping("/removeMedrecordImage")
	public RespondResult removeMedrecordImage(String firstGuid, String fileHash, Model model){
		int result = 0;
		try{
			result = medicalRecordScanService.removeMedRecordImage(firstGuid, fileHash);
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result = -1;
		}
		if(result == 2){
			
			return new RespondResult(true, RespondResult.successCode, "删除病案图片成功", result);
		}else{
			return new RespondResult(false, RespondResult.errorCode, "删除病案图片失败", result);
		}
		
	}
	
	@ResponseBody
	@RequestMapping("/imgSort")
	public RespondResult imgSort(String fileHash,String sortIndex) {
		RespondResult result = null;
		try {
			medicalRecordScanService.updateScanFilrOriginalName(fileHash,sortIndex);
			result = new RespondResult(true, RespondResult.successCode, "修改序列成功", null);
		} catch (Exception e) {
			e.printStackTrace();
			result = new RespondResult(false, RespondResult.errorCode, "修改序列失败", null);
			
		}
		return result;
	}
	
}
